package cn.HL.basic.service.impl;

import cn.HL.basic.constants.BaseConstant;
import cn.HL.basic.dto.LoginDto;
import cn.HL.basic.dto.RegisterDto;
import cn.HL.basic.dto.WechatDto;
import cn.HL.basic.exception.BusinessException;
import cn.HL.basic.jwt.JwtUtils;
import cn.HL.basic.jwt.LoginResult;
import cn.HL.basic.jwt.RsaUtils;
import cn.HL.basic.service.ILoginService;
import cn.HL.basic.util.AjaxResult;
import cn.HL.basic.util.HttpClientUtils;
import cn.HL.basic.util.MD5Utils;
import cn.HL.basic.util.StrUtils;
import cn.HL.system.domain.Menu;
import cn.HL.system.mapper.MenuMapper;
import cn.HL.system.mapper.PermissionMapper;
import cn.HL.user.domain.Logininfo;
import cn.HL.user.domain.User;
import cn.HL.user.domain.Wxuser;
import cn.HL.user.mapper.LogininfoMapper;
import cn.HL.user.mapper.UserMapper;
import cn.HL.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public Map<String, Object> accountLogin(LoginDto dto) {
        //1.先接收所有的参数
        String password = dto.getPassword();
        Integer type = dto.getType();
        String username = dto.getUsername();
        //空校验
        if(StringUtils.isEmpty(password)||StringUtils.isEmpty(type)||StringUtils.isEmpty(username)){
            throw new BusinessException("参数不能为空哦");
        }
        //通过账户名去查找  username 邮箱 电话   ,type
        Logininfo logininfo=logininfoMapper.loadByUsernameAndTpye(username,type);
        //没找到
        if(logininfo==null){
            throw new BusinessException("用户不存在");
        }
        //找到了比较密码是否一致 先获取盐值
        String salt = logininfo.getSalt();
        // 拼接密码
        String md5 = MD5Utils.encrypByMd5(password + salt);
        //比较密码是否一致 (不一致)
        if(!md5.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误");
        }

       return  loginSuccessHandler(logininfo);





        /*//登录成功
        String token = UUID.randomUUID().toString();
        //存放到redis里面去  key  uuid  vaule logininfo
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //返回token和logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //为了防止有人恶意得到密码和盐值 所以清空盐值和密码
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);*/
        //返回给前端
       /* return map;*/
       /* return null;*/
    }

    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        LoginResult loginResult = new LoginResult();
        loginResult.setLogininfo(logininfo);
        if(logininfo.getType()==0){
            //获取权限
            List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
            //获取菜单
            List<Menu> menus=menuMapper.loadMenuByLogininfoId(logininfo.getId());
            loginResult.setMenus(menus);
            loginResult.setPermissions(permissions);
        }
        //生成jwt串
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
        String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginResult, privateKey, 30);
        Map<String, Object> map = new HashMap<>();
        map.put("token",jwtStr);
        map.put("menus",loginResult.getMenus());
        map.put("permissions",loginResult.getPermissions());
        map.put("logininfo",loginResult.getLogininfo());
        return map;
    }

    /**
     *微信扫码
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WechatDto dto) {
        String code = dto.getCode();
        //空校验
        if(StringUtils.isEmpty(code)){
            throw  new BusinessException("微信出错,请稍后重试");
        }
//        1.通过code从微信获取token+openid       ②
        String tokenUrl= BaseConstant.WeChatConstants.TOKEN_URL
                .replace("APPID", BaseConstant.WeChatConstants.APPID)
                .replace("SECRET",BaseConstant.WeChatConstants.SECRET)
                .replace("CODE", code);;
            //发起get请求获取token+openid
        String tokenStr  = HttpClientUtils.httpGet(tokenUrl);
        //把微信返回给我们的转为json对象
        JSONObject jsonObject = JSONObject.parseObject(tokenStr);
        //从对象中获取token+openid
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        //通过openId去查询t_wxuser是否存在
       Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
//        2.通过openid查询t_wxuser表，判断是否wxuser存在并且user_id不为空
        if(wxuser!=null&&wxuser.getUserId()!=null){
            //        2.1 有，且userId存在，直接免密登录===第二次之后的扫码登录
            Logininfo logininfo=logininfoMapper.loadByUserId(wxuser.getUserId());
            /*String token = UUID.randomUUID().toString();
            //存放到redis里面去  key  uuid  vaule logininfo
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
            //返回token和logininfo
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            //为了防止有人恶意得到密码和盐值 所以清空盐值和密码
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);*/
            return AjaxResult.me().setResultObj(loginSuccessHandler(logininfo));
        }
//        2.2 没有，这里应该让浏览器跳转到绑定页面，让它自己输入账号和密码来完成绑定
        String binderParams="?accessToken="+accessToken+"&openId="+openId;
//        返回token+openid
        return  AjaxResult.me().setResultObj(binderParams).setSuccess(false);
    }

    /**
     * 绑定账户
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> binder(WechatDto dto) {
        //空校验
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
        String password = dto.getPassword();
        String phone = dto.getPhone();
        if(StringUtils.isEmpty(accessToken)||StringUtils.isEmpty(openId)||StringUtils.isEmpty(password)||StringUtils.isEmpty(phone)){
            throw new BusinessException("参数不能为空哦!!");
        }
//        1.根据username 查询t_user是否曾今已经存在
        User user = userMapper.loadByPhone(phone);
        Logininfo logininfo=null;
        if(user!=null){
            //比较密码
            String salt = user.getSalt();
            //设置面密码
            String userPassword = MD5Utils.encrypByMd5(dto.getPassword()+salt);
            if(!user.getPassword().equals(userPassword)){
                throw new BusinessException("密码错误,请重新找回");
            }
            //        1.1 存在 查询出来，等着绑定
            logininfo = logininfoMapper.loadById(user.getLogininfoId());
        }else{
            //        1.2 不存在 生成新的t_user + t_logininfo

            //先新增LoginInfo 要获取到的自增id
           user = dto2User(dto);
            logininfo =user2Logininfo(user);
            //新增logininfo
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            //新增user
            userMapper.save(user);
        }
//        2.根据token + openid 去微信查询微信的用户基本信息   ③
        String wxUserUrl=BaseConstant.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN",dto.getAccessToken())
                .replace("OPENID",dto.getOpenId());
//        3.根据微信的用户基本信息生成t_wxuser
        String wxUserStr  = HttpClientUtils.httpGet(wxUserUrl);
        Wxuser wxuser = JSON.parseObject(wxUserStr, Wxuser.class);
        //        4.t_wxuser绑定t_user
        wxuser.setUserId(user.getId());
        //        5.保存t_wxuser（完成了整个绑定流程）
        wxuserMapper.save(wxuser);

        /*String token = UUID.randomUUID().toString();
        //存放到redis里面去  key  uuid  vaule logininfo
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //返回token和logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //为了防止有人恶意得到密码和盐值 所以清空盐值和密码
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);*/
        return loginSuccessHandler(logininfo);

//        6.直接免密登录
    }


    /**
     * 数据的拷贝
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //拷贝数据只要两个对象里面的有的属性名一样就能拷贝
        BeanUtils.copyProperties(user,logininfo);
        //设置为用户
        logininfo.setType(1);
        return logininfo;
    }
    /**
     * 数据的拷贝
     * @return
     */
    private User dto2User(WechatDto dto) {
        User user = new User();
        user.setPhone(dto.getPhone());
        user.setUsername(dto.getPhone());
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //设置面密码
        String password = MD5Utils.encrypByMd5(dto.getPassword()+salt);
        user.setPassword(password);
        return user;

    }
}
